package org.micropayment.consumer.oauth.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.security.AuthenticationException;
import org.springframework.security.oauth.consumer.token.OAuthConsumerToken;
import org.springframework.security.oauth.consumer.token.OAuthConsumerTokenServices;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 *
 * @author jj
 */
public class MicropaymentConsumerTokenServices implements OAuthConsumerTokenServices {

    public static final String KEY_PREFIX = "OAUTH_TOKEN";

    private HttpSession session;
    private String transaction_timestamp = "transaction_timestamp";

    public MicropaymentConsumerTokenServices(HttpSession session) {
        this.session = session;
    }

    public OAuthConsumerToken getToken(String resourceId) throws AuthenticationException {
        MicropaymentOAuthConsumerToken token = (MicropaymentOAuthConsumerToken)
                this.session.getAttribute(KEY_PREFIX + "#" + resourceId);
        if (token != null && token.getToken().isAccessToken()) {
            //New Transaction
            return null;
        }
        if (token == null) return null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String transactionTimestamp =
                request.getParameter(transaction_timestamp);
        if (transactionTimestamp != null) {
            return null;
        } else {
            return token.getToken();
        }
    }

    public void storeToken(String resourceId, OAuthConsumerToken token) {
        MicropaymentOAuthConsumerToken micropaymentToken = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String transactionTimestamp = request.getParameter(transaction_timestamp);
        if (transactionTimestamp == null) {
            micropaymentToken = (MicropaymentOAuthConsumerToken)
                this.session.getAttribute(KEY_PREFIX + "#" + resourceId);
            micropaymentToken.setToken(token);
        } else {
            micropaymentToken = new MicropaymentOAuthConsumerToken(token);
            micropaymentToken.setTransaction_timestamp(transactionTimestamp);
        }
        this.session.setAttribute(KEY_PREFIX + "#" + resourceId, micropaymentToken);
    }

}
